#include "bsp_adc.h"
#include "../../stdio/include/stdio.h"
#include "../delay/bsp_delay.h"
#include "../gpio/bsp_gpio.h"

void ADC_Init(ADC_Type *base) {
  IOMUXC_SetPinMux(IOMUXC_GPIO1_IO06_GPIO1_IO06, 0);
  IOMUXC_SetPinConfig(IOMUXC_GPIO1_IO06_GPIO1_IO06, 0xF080);

  gpio_pin_config_t config;
  config.direction = kGPIO_DigitalInput;
  config.interruptMode = kGPIO_IntRisingEdge;
  config.outputLogic = 0;
  gpio_init(GPIO1, 6, &config);

  base->CFG = 0;
  base->CFG |= (0x1 << 14);
  base->CFG |= (0x2 << 8);
  base->CFG |= (0x1 << 7);

  ADC_Select_Channel(base, 6);
  ADC_IRQ_Enable(base);

  ADC_Calibration(base);
}

/**
 * @brief 校准ADC
 *
 * @param base ADC_Type
 * @return unsigned char 成功1 失败0
 */
unsigned char ADC_Calibration(ADC_Type *base) {
  base->GC |= (0x1 << 7);
  while ((base->GC & (0x1 << 7)) == 1) {
  }
  if ((base->GS & (0x1 << 1)) == 1) {
    base->GS |= (0x1 << 1);
    return 0;
  }
  if ((base->HS & (0x1 << 0)) == 0) {
    return 0;
  }
  return 1;
}

/**
 * @brief ADC中断开启
 *
 * @param base ADC_Type
 */
void ADC_IRQ_Enable(ADC_Type *base) { base->HC[0] |= (0x1 << 7); }

/**
 * @brief 开启对应通道
 *
 * @param base ADC_Type
 * @param n
 */
void ADC_Select_Channel(ADC_Type *base, unsigned char n) {
  base->HC[0] &= ~(0x1f << 0);
  base->HC[0] |= (n << 0);
}

/**
 * @brief
 *
 * @param giccIar
 * @param param
 */
void ADC_handler(unsigned int giccIar, void *param) {
  unsigned short res = 0;
  res = ADC1->R[0] & 0xfff;
  res = res * 3300 / 256;
  printf("%d\r\n", res);
  ADC_Select_Channel(ADC1, 6);
  delay_ms(500);
}